#!-*- encoding:utf8 -*-
import MySQLdb
import threading
import traceback

class DbObject:
    
    #数据库是共享互斥异步的
    def __init__(self, host, user, passwd, database, port=3306, charset="utf8", dict=False):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = database
        self.port = port
        self.charset = charset
        self.dict = dict

        self.conn()
        self._l = threading.Lock()

    def conn(self):
        self._conn = MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, \
                        db=self.db, port=self.port, charset=self.charset)
        if self.dict:
            self._cursor = self._conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
        else:
            self._cursor = self._conn.cursor()
        self._cursor.execute("SET NAMES 'utf8'")


    def executeSql(self ,sql):
        self._l.acquire()
        try:
            self._conn.ping()
        except:
            self.conn()       
        try:
            sql = sql.encode("utf-8")
            res = self._cursor.execute(sql)
            #logging.info("execute: %s, status: %s" % (sql, res))
        except:
            traceback.print_exc()
            res = False
        #finally:
        self._l.release()
        return res
     
    def executeSqlRet(self ,sql):
        self._l.acquire()
        try:
            sql = sql.encode("utf-8")
            stat = self._cursor.execute(sql)
            #logging.info("execute: %s, status: %s" % (sql, stat))
            res = self._cursor.fetchall()
        except:
            traceback.print_exc()
            res = False
        #finally:
        self._l.release()
        return res
     
    def __del__(self):
        self._cursor.close()
